package com.global.emc.spring.exception.handler.messages;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;

import com.global.emc.core.exception.IEMCException;
import com.global.emc.core.exception.impl.FormValidationEMCException;

/**   
 *  
 * @Description:  [使用spring容器解析FormValidationEMCException类型异常消息]   
 * @Author:       [Joly]   
 * @CreateDate:   [2014年1月7日 下午12:00:56]   
 * @UpdateUser:   [Joly]   
 * @UpdateDate:   [2014年1月7日 下午12:00:56]   
 * @UpdateRemark: [说明本次修改内容]  
 * @Version:      [v1.0] 
 *    
 */
public class FormValidationEMCExceptionMessagesHandler extends EMCExceptionMessagesHandler{
	
	@Override
	public boolean supports(IEMCException emcException) {
		return emcException instanceof FormValidationEMCException;
	}

	@Override
	public void resolverMessages(IEMCException emcException,Locale locale) {
		FormValidationEMCException formValidationEMCException=(FormValidationEMCException)emcException;
		BindException bindException = (BindException)formValidationEMCException.getCause();
		
		Map<String, List<String>> fieldErrors = formValidationEMCException.getFieldErrors();
		for(Map.Entry<String, List<String>> field : fieldErrors.entrySet()){
			String key=field.getKey();
			List<FieldError> bindFieldErrors = bindException.getFieldErrors(key);
			List<String> fieldErrorMessages = new ArrayList<String>();
			for(FieldError fieldError : bindFieldErrors){
				try {
					String localizedMessage=super.getApplicationContext().getMessage(fieldError, locale);
					fieldErrorMessages.add(localizedMessage);
				} catch (Exception e) {
					this.logger.error("IEMCExceptionResolver error,message:"
							+ (fieldError)
							+ " in the locale source file is not find");
				}
			}
			fieldErrors.put(key, fieldErrorMessages);
		}
		
		super.resolverMessages(formValidationEMCException, locale);
	}

	
	
}
